#!/bin/bash
# PostgreSQL 部署脚本

set -e

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }
warn() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] ⚠️  $*"; }
err() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] ❌ $*" >&2; }

echo "=========================================="
echo "部署 PostgreSQL"
echo "=========================================="
echo ""

# 设置 KUBECONFIG
if [ -f /etc/rancher/k3s/k3s.yaml ]; then
    export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
elif [ -f ~/.kube/config ]; then
    export KUBECONFIG=~/.kube/config
fi

# 1. 清理旧部署
log "步骤 1/7: 清理旧部署..."
kubectl delete statefulset postgresql --ignore-not-found=true
kubectl delete svc postgresql --ignore-not-found=true
kubectl delete pvc postgresql-pvc --ignore-not-found=true
kubectl delete pvc postgresql-data-postgresql-0 --ignore-not-found=true
log "✓ 旧部署已清理"
echo ""

# 2. 修复 PV 状态（如果是 Released，清除绑定信息）
log "步骤 2/7: 检查并修复 PV 状态..."
PV_STATUS=$(kubectl get pv postgresql-pv -o jsonpath='{.status.phase}' 2>/dev/null || echo "NotFound")
if [ "$PV_STATUS" = "Released" ]; then
    log "PV 状态为 Released，清除绑定信息..."
    kubectl patch pv postgresql-pv -p '{"spec":{"claimRef": null}}'
    log "✓ PV 已重置为 Available"
elif [ "$PV_STATUS" = "Available" ]; then
    log "✓ PV 状态正常"
elif [ "$PV_STATUS" = "NotFound" ]; then
    log "PV 不存在，创建 PV..."
    kubectl apply -f k8s/storage/pv.yaml
    log "✓ PV 已创建"
else
    warn "PV 状态: $PV_STATUS"
fi
echo ""

# 3. 创建 Secret
log "步骤 3/7: 创建 Secret..."
kubectl apply -f k8s/postgresql/secret.yaml
log "✓ Secret 已创建"
echo ""

# 4. 创建 PVC
log "步骤 4/7: 创建 PVC..."
kubectl apply -f k8s/postgresql/pvc.yaml
log "✓ PVC 已创建"
echo ""

# 5. 部署 StatefulSet
log "步骤 5/7: 部署 StatefulSet..."
kubectl apply -f k8s/postgresql/statefulset.yaml
log "✓ StatefulSet 已部署"
echo ""

# 6. 创建 Service
log "步骤 6/7: 创建 Service..."
kubectl apply -f k8s/postgresql/service.yaml
log "✓ Service 已创建"
echo ""

# 7. 等待 Pod 就绪
log "步骤 7/7: 等待 PostgreSQL Pod 启动（最多 5 分钟）..."
kubectl wait --for=condition=ready pod -l app=postgresql --timeout=300s || {
    err "Pod 启动失败！"
    echo ""
    log "Pod 状态："
    kubectl get pod -l app=postgresql -o wide
    echo ""
    log "Pod 详细信息："
    kubectl describe pod -l app=postgresql | tail -30
    echo ""
    log "Pod 日志："
    kubectl logs -l app=postgresql --tail=50
    exit 1
}
log "✓ PostgreSQL Pod 已就绪"
echo ""

# 显示状态
echo "=========================================="
echo "部署完成"
echo "=========================================="
kubectl get pod -l app=postgresql -o wide
echo ""
kubectl get pvc postgresql-pvc
echo ""
kubectl get svc postgresql
echo ""

PG_POD=$(kubectl get pod -l app=postgresql -o jsonpath='{.items[0].metadata.name}')
NODE_IP=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
PG_PASSWORD=$(kubectl get secret postgresql-secret -o jsonpath='{.data.postgres-password}' | base64 -d)

log "连接信息："
log "  集群内部: postgresql:5432"
log "  外部访问: $NODE_IP:30432"
log "  用户名: postgres"
log "  密码: $PG_PASSWORD"
log "  数据库: xy_portal"
echo ""

